<?php

namespace ShowStop\SecurityBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Security\Core\SecurityContext;
use Fp\OpenIdBundle\Security\Core\Authentication\Token\OpenIdToken;
use ShowStop\UserBundle\Entity\User;
use ShowStop\UserBundle\Entity\Role;

class SecurityController extends Controller
{

	/**
	* @Route("/login", name="_login")
	* @Template()
	*/
	public function loginAction()
    {
        $request = $this->getRequest();
        $session = $request->getSession();

        // get the login error if there is one
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
        } 

        return $this->render('ShowStopSecurityBundle:Security:login.html.twig', array(
            // last username entered by the user
            'last_username' => $session->get(SecurityContext::LAST_USERNAME),
            'error'         => $error,
        )); 
    }
    
	/**
     * @Route("/login_check", name="login_check")
     */
    public function loginCheckAction()
    {
        // The security layer will intercept this request
    }
    
    /**
    * @Route("/facebook_check", name="facebook_check")
    * @Template()
    */
    public function facebookCheckAction() {
    	// The security layer will intercept this request
    }
    
    public function findUserByEmail($email)
    {
    	$em = $this->getDoctrine()->getEntityManager();
    	$query = $em->createQuery("SELECT u FROM
        		         ShowStopUserBundle:User u
        		         WHERE u.email = :email")
    				->setParameters(array('email' => $email ));
    	
    	$user =  $query->getOneOrNullResult();
    	
    	return $user;
    }
    
    /**
    * @Route("/openid_approve_user", name="openid_approve_user")
    * @Template()
    */
    public function approveUserAccountAction(Request $request)
    {
    	$tokenPersister = $this->get('fp_openid.security.authentication.token_persister');
    
    	$token = $tokenPersister->get();
    	
    	$user = $this->findUserByEmail( $token->getAttribute('contact/email') );
    	
    	if( empty( $user ) ) {
    		$user = new User();
    		
    		$em = $this->getDoctrine()->getEntityManager();
    		
    		
    		$attributes = $token->getAttributes();
    		
    		$em = $this->getDoctrine()->getEntityManager();
    		$query = $em->createQuery( "SELECT r FROM ShowStopUserBundle:Role r WHERE r.name = 'ROLE_USER'" );
    		$role = $query->getSingleResult();
    		$user->getUserRoles()->add( $role );
    		
    		$user->setOpenIdData( $attributes );
    		
    		$em->persist( $user );
    		$em->flush();
    	}
    	
    	// IMPORTANT: It is required to set a user to token (UserInterface)
    	$newToken = new OpenIdToken($token->getIdentifier(), $user->getRoles());
    	$newToken->setUser($user);
    
    	$tokenPersister->set($newToken);
    
    	// IMPORTANT: It is required make a redirect to `login_check` with parameter `openid_approved`
    	return $this->redirect($this->generateUrl('login_check', array('openid_approved' => 1)));
    }
    
}
